package com.sunshine.wrongquestionset.activity.my_subject

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import com.google.android.material.textview.MaterialTextView
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.main.SearchBean
import com.sunshine.wrongquestionset.callback.OnClickListener
import com.sunshine.wrongquestionset.room.entity.QuestionSetEntity
import com.sunshine.wrongquestionset.room.entity.SubjectEntity
import com.sunshine.wrongquestionset.view.HasEmptyRecyclerAdapter

/**
 * @author sunshine
 * @date 2021/3/29
 */
class MySubjectAdapter(
    private var list: ArrayList<SubjectEntity>?,
    private val viewModel: MySubjectViewModel,
    private val owner: LifecycleOwner,
    private val callback: OnClickListener
): HasEmptyRecyclerAdapter<MySubjectAdapter.ViewHolder>(list) {

    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        val root: MaterialCardView = itemView.findViewById(R.id.item_subject_root)
        val description: MaterialTextView = itemView.findViewById(R.id.description)
        val subjectName: MaterialTextView = itemView.findViewById(R.id.subject_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_my_subject, parent, false))
    }

    override fun getItemCount(): Int {
        return list?.size ?: 0
    }

    fun setFilter(list: ArrayList<SubjectEntity>?) {
        this.list = list
        notifyDataSetChanged(list)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.subjectName.text = list!![position].name
        viewModel.getSetCountInSubjectId(list!![position].id).observe(owner, Observer {
            holder.description.text = "共有${it}个错题本"
        })
        holder.root.setOnClickListener {
            callback.onClick(position)
        }
    }
}